﻿using System;
using UnityEngine;
using System.Collections.Generic;
using FibMatrix;
using FM_Mono;

[IgnoreGen]
public class MeshResourcePackLoader :MonoBehaviour
{
	[Serializable]
	public struct PackGroup
	{
		public List<MeshRenderer> renderers;
		public string resPackPath;
	}

	public PackGroup[] packGroups;

	private int _currentIndex = 0;

	// Update is called once per frame
	void Start()
	{
		LoadNextResource();
	}

	void Update()
	{
		LoadNextResource();
	}

	void LoadNextResource()
	{
		if (packGroups != null && _currentIndex < packGroups.Length)
		{
			MeshResourcePack pack = null;
#if !DISABLE_SYNC_LOAD
			pack = ResourceFacade.instance.LoadObject(packGroups[_currentIndex].resPackPath) as MeshResourcePack;
#else
			Debug.LogError($"MeshResourcePackLoader not supported in async yet");
			enabled = false;
			return;
#endif
			if (pack == null)
			{
				++_currentIndex;
				LoadNextResource();
			}
			else
			{
				AddLoadedMeshResPack(pack);
			}
		}
		else
		{
			this.enabled = false;
		}
	}

	void AddLoadedMeshResPack(MeshResourcePack pack)
	{
		if (pack != null)
		{
			ResourceFacade.AddAutoUnloadObject(pack);
			PackGroup group = packGroups[_currentIndex];
			List<MeshRenderer> renderers = group.renderers;
			int count = renderers != null ? renderers.Count : 0;
			for (int i = 0; i < count; ++i)
			{
				renderers[i].sharedMaterial = pack.mat;
				MeshFilter filter = renderers[i].GetComponent<MeshFilter>();
				filter.sharedMesh = pack.mesh;
			}
		}
		++_currentIndex;
		LoadNextResource();
	}

}
